require 'Common/define'
require 'Logic/Config'
require 'Common/functions'
require "Net/mythicDungeonsHandler"

UIMythicDungons = {};
HelperFunc.SetUIEnv(UIMythicDungons)
local this = UIMythicDungons;

this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;

this.numLevelText = nil;
this.numLevelBtn = nil;
this.chooseLayerItem = nil;
this.btnBackBtn = nil;
this.objSelectGroup = nil;
this.objLayerGroup = nil;
this.objLayerItem = nil;
this.imgCostIcon = nil;
this.txtCostCount = nil;
this.btnSelectBtn = nil;
this.objEnterGroup = nil;
--this.txtLayer = nil;
this.layerPower = nil;
this.txtTime = nil;
this.btnEnterButton = nil;
this.controllerGroup = nil;
this.title = nil;
this.clicks = {};

this.selectLayerId = 0;
this.tableLayerObj = {};
this.timer = nil;

this.itemCg = nil;
this.mythicConfig = nil;
this.mythicMaxLayer = 0;
this.comPower = nil;

this.curPlayRound = 0; --当前播放回合
this.curFormations = {}; -- 当前阵容
this.btntip = nil;
this.btnGoShop = nil

this.dungeonPower = nil;--地牢敌人战斗力
this.powerStateController = nil;--0自己战力大于等于秘境 1自己战力小于秘境
this.ifHaveKeyController = nil;--是否有入场券表现

this.enterAni = nil;
this.backFun = nil;
this.isEnterAni = false;
this.timerId = nil

this.rewardList = nil;--展示奖励列表
this.rewardRandomList = nil;--展示随机奖励列表
this.rewardListData = {};--展示奖励列表数据
this.rewardRandomListData = {};--展示随机奖励列表数据

this.taskRewardDatas = {}--里程碑奖励数据
this.taskDecText = nil;
this.taskListReward = nil;
this.taskShowController = nil;
this.lastBattle = nil
this.maxBattle = nil
this.battleCtrl = nil
this.btnLast = nil
this.btnMax = nil
this.btn_Rush = nil
this.rush_State = nil
this.mainReward = nil
this.LockTip = nil
this.lockItem = nil
this.lockCtrl = nil
this.lockList = nil
this.lockTitle = nil
this.lockData = {}
this._lockData = {};
function UIMythicDungons.Init(fun, isAni)
    --todo 应该小写 暂时先大写
    if itemCg == nil then
        itemCg = G.dataTable["t_item"][tostring(CurrencyEnum.MythicDungoesTicket)];
    end
    isEnterAni = isAni;
    backFun = fun;
    if not comPower then
        comPower = G.dataTable["t_mythicdungeonsmonsterteam"];
    end
    if mythicConfig == nil then
        mythicConfig = G.dataTable["t_mythicdungeons"];
        mythicMaxLayer = 0;
        for key, value in pairs(mythicConfig) do
            if mythicMaxLayer < value.f_MythicDungeonsLevelID then
                mythicMaxLayer = value.f_MythicDungeonsLevelID
            end
        end
    end
    local name, packageName = getUIName(PanelNames.UIMythicDungons);
    panelMgr:ShowUI(name, packageName, this.onCreate, Config.useLocalUI);
end

function UIMythicDungons.onCreate(obj)
    gameObject = obj;

    if not hasInit then
        hasInit = true;
        controllerGroup = obj:GetController("c1");
        this.ctrlIfShowLevel = obj:GetController("ifShowLevel")
        enterAni = obj:GetTransition("PageOpen");
        title = obj:GetChild("n1"):GetChild("title");
        btnBackBtn = obj:GetChild("BackBtn");
        objSelectGroup = obj:GetChild("SelectGroup");
        objLayerGroup = obj:GetChild("list");
        --objLayerItem = obj:GetChild("SelectGroup/LayerGroup/Viewport/Content/LayerItem").gameObject;
        imgCostIcon = obj:GetChild("CostIcon");
        txtCostCount = obj:GetChild("CostCount");
        btnSelectBtn = obj:GetChild("SelectBtn");
        numLevelBtn = obj:GetChild("numLevel");
        numLevelText = numLevelBtn:GetChild("title");
        objEnterGroup = obj:GetChild("EnterGroup");
        btnAdd = obj:GetChild("btnAdd")
        btnReduce = obj:GetChild("btnReduce")
        resCom = obj:GetChild("key");
        resComAdd = resCom:GetChild("btnJump");
        mainReward = obj:GetChild("mainReward")
        rewardList = obj:GetChild("listReward");--选择层数后的显示通关奖励
        rewardList.itemRenderer = this.renderRewardItem;
        rewardRandomList = obj:GetChild("listRewardRandom");--选择层数后的显示通关随机奖励
        rewardRandomList.itemRenderer = this.renderDropRewardItem;

        --local showItem = obj:GetChild("item");
        --local con = showItem:GetController("c1");
        --con.selectedIndex = 0;
        --txtLayer = showItem:GetChild("LayerText");
        --layerPower = showItem:GetChild("PowerText");
        txtTime = obj:GetChild("TimeText");
        btnEnterButton = obj:GetChild("EnterButton");
        btntip = obj:GetChild("btnTip");
        btnReward = obj:GetChild("btnRewardList");
        this.btnGoShop = obj:GetChild("btnGoShop")
        this.text_power = obj:GetChild("text_power");
        dungeonPower = obj:GetChild("levelPower");
        this.sourceUIobj = obj:GetChild("UISourceMultiple");
        this.showSourceController = obj:GetController("showSource")
        powerStateController = obj:GetController("power");
        ifHaveKeyController = obj:GetController("ifHaveKey");
        btnLast = obj:GetChild("level"):GetChild("last")
        btnMax = obj:GetChild("level"):GetChild("highest")
        lastBattle = btnLast:GetChild("LayerText")
        maxBattle = btnMax:GetChild("LayerText")
        battleCtrl = obj:GetChild("level"):GetController("state")
        taskDecText =  obj:GetChild("3");--里程碑描述
        taskListReward =  obj:GetChild("listReward1");--里程碑奖励
        taskListReward.itemRenderer = this.refreshTaskReward;
        this.taskShowController = obj:GetController("ifshow")
        btn_Rush = obj:GetChild("Btn_Rush")
        rush_State = btn_Rush:GetController("type")
        this.LockTip = obj:GetChild("Text_UnlockTips")
        this.lockItem = obj:GetChild("Btn_Unlockitem")
        this.lockCtrl = obj:GetController("UnlockTips")
        this.lockList = obj:GetChild("Com_UnlockTips"):GetChild("list")
        this.lockTitle = obj:GetChild("Com_UnlockTips"):GetChild("title")
        tableLayerObj = {};
        selectLayerId = 0;
        --local childCount = objLayerGroup.transform.childCount;
        --
        --for i = 1, childCount do
        --    local obj = objLayerGroup.transform:GetChild(i-1).gameObject;
        --    table.insert(tableLayerObj,obj);
        --end
        this.addEvent();
    end
    lockData = decodeJsonStrToTabel(G.dataTable["t_global"]["591"].f_string_value)
    this.lockList.itemRenderer = this.SetLockItem
    BattlePlaybackManager.ClearMultiFightData()
    this.refresh();
    if isEnterAni then
        enterAni:Play();
    end
    logicMgr.FuncOpenManager.refreshMainReward(this.mainReward,Config.FuncOpenType.Mythic)
end

function UIMythicDungons.addEvent()
    btnReward.onClick:Add(function()
        if selectLayerId == 0 then
            UISysTips.AddMsg(getLanguage("MythicDungeons_tips11"));
            return
        end

        showUI(PanelNames.UIMythicDungeonsReward, selectLayerId);
    end);
    btnBackBtn.onClick:Add(this.onClickBack);
    btnSelectBtn.onClick:Add(this.onClickSelect);
    btnEnterButton.onClick:Add(this.onClickEnter);
    btntip.onClick:Add(this.ShowTips);
    btnGoShop.onClick:Add(this.ClickShop);
    btnAdd.onClick:Add(this.ClickAdd);
    btnReduce.onClick:Add(this.ClickReduce);
    this.resComAdd.onClick:Add(this.onClickGetItem);
    btnLast.onClick:Add(this.ClickLast)
    btnMax.onClick:Add(this.ClickMax)
    btn_Rush.onClick:Add(this.GoRush)
end

function UIMythicDungons.removeEvent()
    btnReward.onClick:Clear();
    btnBackBtn.onClick:Clear();
    btnSelectBtn.onClick:Clear();
    btnEnterButton.onClick:Clear();
    btntip.onClick:Clear();
    btnGoShop.onClick:Clear();
    btnAdd.onClick:Clear();
    btnReduce.onClick:Clear();
    this.resComAdd.onClick:Clear();
    btnLast.onClick:Clear()
    btnMax.onClick:Clear()
    btn_Rush.onClick:Clear()
end

function UIMythicDungons.LocalListenEvent()
    ListenEvent(Config.EventType.Fresh_MythicSelectLayer, this.onEnterFormation);
    ListenEvent(Config.EventType.Fresh_MythicSelectBuff, this.onSelectBuffSuccess);
    ListenEvent(Config.EventType.Fresh_Bag,this.updateSource);
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    ListenEvent(Config.EventType.Fresg_RushItem,this.SetItem)
    --ListenEvent(Config.EventType.Fresh_MythicBattleResult, this.onBattleResult);
end

function UIMythicDungons.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_MythicSelectLayer,this.onEnterFormation);
    CloseEvent(Config.EventType.Fresh_MythicSelectBuff,this.onSelectBuffSuccess);
    CloseEvent(Config.EventType.Fresh_Bag,this.updateSource);
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    CloseEvent(Config.EventType.Fresg_RushItem,this.SetItem)
    --CloseEvent(Config.EventType.Fresh_MythicBattleResult);

    if timer ~= nil then
        timer:Stop();
    end
end

function UIMythicDungons.SetLockItem(idx,obj)
    local tip = obj:GetChild("title")
    local item = obj:GetChild("n2")
    local data = this._lockData[idx+1]
    tip.text = string.format(getLanguage("MythicDungonsTips"),data[1])
    local itemScript = CtrlManager.GetCtrl(PanelNames.Item);
    itemScript.initData(item,{["itemModelId"] = data[2]})
end

function UIMythicDungons.SetItem()
    local getNum = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MythicDungoesTicket);
    resCom:GetChild("title").text = getNum;
end

function UIMythicDungons.OnDisable()
    hasInit = false
    this.removeEvent();
    this.clicks = {}
    if timerId then
        utimer.remove(timerId)
        timerId = nil
    end
end

function UIMythicDungons.OnDestroy()
    hasInit = false
    this.removeEvent();
    this.clicks = {}
    if timerId then
        utimer.remove(timerId)
        timerId = nil
    end
end

function UIMythicDungons.OnEnable()
    AudioManager.SetSwitch("battle_steps", "arr")
    FightManager.SetBGMSwitchByBattleType(EnumConst.FightTypeConst.INSTANCE)
    AudioManager.SetSwitch("Battle_SwitchGroup", "mystery")
    this.LocalListenEvent();
    this.needShowHeadMenu = nil;
    if isOpenUI(PanelNames.UIHeadMenu) then
        this.needShowHeadMenu = true;
        closeUI(PanelNames.UIHeadMenu);
    end
end

function UIMythicDungons.OnDisable()
    this.LocalCloseEvent();
    if timerId then
        utimer.remove(timerId)
        timerId = nil
    end
end

function UIMythicDungons.GoRush()
    local lastLayer = logicMgr.MythicDungeonsManager.LastLayer()
    if logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MythicDungoesTicket)>0 then
        if lastLayer > 0 then
            showUI(PanelNames.UISweep)
        else
            UISysTips.AddMsg(getLanguage("MythicDungeons_Sweep10"))
            return
        end
    else
        local name = logicMgr.ItemManager.GetItemName(CurrencyEnum.MythicDungoesTicket)
        if name then
            UISysTips.AddMsg(name .. getLanguage("MythicDungeons_tips9"))
        end
        return
    end
end

function UIMythicDungons.ShowTips()
    local txts = {};
    txts["title"] = "HelpTitle2";
    txts["des"] = "HelpDes2";
    txts["story"] = "FunctionStory302";
    showUI(PanelNames.CommonTips, txts);
end
function UIMythicDungons.refreshRewardList()
    if selectLayerId ~= 0 then
        local cfg = decodeJsonStrToTabel(G.dataTable["t_mythicdungeonsdrop"][tostring(selectLayerId)]["f_RewardResS"]);
        local dropCfg = decodeJsonStrToTabel(G.dataTable["t_mythicdungeonsdrop"][tostring(selectLayerId)]["f_RewardEquipShowS"])
        rewardListData = cfg;
        rewardRandomListData =dropCfg;
        rewardList.numItems = #cfg;
        rewardRandomList.numItems = #dropCfg;
    end
end

function UIMythicDungons.ClickLast()
    this.onClickSelectLayer(btnLast,logicMgr.MythicDungeonsManager.LastLayer())
end

function UIMythicDungons.ClickMax()
    this.onClickSelectLayer(btnMax, this.maxCount)
end

function UIMythicDungons.renderRewardItem(idx, obj)
    local data = logicMgr.ItemManager.getItemConstDatabyModelId(rewardListData[idx + 1][1]);
    local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
    itemCtr.initData(obj, data);
end

function UIMythicDungons.renderDropRewardItem(idx, obj)
    local data = logicMgr.ItemManager.getItemConstDatabyModelId(rewardRandomListData[idx + 1]);
    local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
    itemCtr.initData(obj, data);
end

function UIMythicDungons.refresh()
    title.text = getLanguage("FunctionName302");
    local maxLayer = logicMgr.MythicDungeonsManager.getMaxLayer();
    local taskInfo = MythicDungeonsManager.checkTaskCfgById(maxLayer);
    this._lockData = {};
    for _,v in ipairs(lockData) do
        if MythicDungeonsManager.getMaxLayer() < v[1] then
            table.insert(this._lockData, v);
        end
    end
    this.lockList.numItems = #this._lockData
    local data = this._lockData[1];
    if data then
        LockTip.text = string.format(getLanguage("MythicDungonsTips"),data[1])
        local itemScript = CtrlManager.GetCtrl(PanelNames.Item);
        itemScript.initData(this.lockItem,{["itemModelId"] = data[2]})
    else
        this.lockCtrl.selectedIndex = 2
    end
    if taskInfo == false then
        taskShowController:SetSelectedIndex(1);
        taskDecText.text = ""
        taskRewardDatas = {}
    else
        taskShowController:SetSelectedIndex(0);
        taskDecText.text = getLanguage(taskInfo.f_TaskDesc)
        taskRewardDatas = decodeJsonStrToTabel(taskInfo.f_Award);
    end

    taskListReward.numItems = #taskRewardDatas;
    this.text_power.text = HelperFunc.FormatResourceNum(logicMgr.HeroManager.GetTopHerosPower(), true);
    if not hasInit then
        return
    end
    if timer ~= nil then
        timer:Stop();
    end
    local lastLayer = logicMgr.MythicDungeonsManager.LastLayer()
    if lastLayer and lastLayer ~=0 then
        battleCtrl.selectedIndex = 1
        lastBattle.text = lastLayer
    else
        battleCtrl.selectedIndex = 0
    end
    if lastLayer > 0 and logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MythicDungoesTicket)>0 then
        rush_State.selectedIndex = 1
    else
        rush_State.selectedIndex = 0
    end
    if logicMgr.MythicDungeonsManager.getLayer() > 0 then
        --numLevelBtn:GetController("ifSelect").selectedIndex = layerId <=0 and 0 or 1;
        this.refreshEnterGroup();
    else
        this.refreshSelectGroup();
    end
end

function UIMythicDungons.refreshSelectGroup()
    controllerGroup.selectedIndex = 1;
    btnEnterButton:GetController("isContinue").selectedIndex = 0;
    btnEnterButton:GetChild("text").text = 1;
    --objSelectGroup:SetActive(true);
    --objEnterGroup:SetActive(false);
    local maxLayer = logicMgr.MythicDungeonsManager.getMaxLayer();

    local allCount = G.dataTable["t_global"]["80"].f_int_value + maxLayer;
    if allCount > mythicMaxLayer then
        allCount = mythicMaxLayer;
    end
    maxBattle.text = allCount
    this.maxCount = allCount
    objLayerGroup.itemRenderer = this.renderItem;
    local showCount = G.dataTable["t_global"]["186"].f_int_value + allCount;
    objLayerGroup.numItems = showCount;

    this.ScrollToView(allCount - 1)
    local selectLayer = 0
    --if selectLayer > 0 then
    --    this.onClickSelectLayer(objLayerGroup:GetChildAt(selectLayer - 1),selectLayer );
    --elseif maxLayer > 0 then
    --    this.onClickSelectLayer(objLayerGroup:GetChildAt(maxLayer - 1),maxLayer );
    --else
    this.onClickSelectLayer(objLayerGroup:GetChildAt(showCount - 1), showCount);

    --end
    --if itemCg ~= nil then
    --    imgCostIcon.url = "ui://ItemAtlas/" .. itemCg.f_Icon;
    --    --resMgr:LoadIconFromPrefab("itemAtlas", itemCg.f_Icon,function(sp)
    --    --    imgCostIcon.sprite = sp;
    --    --end);
    --end
    local getNum = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MythicDungoesTicket);
    local hasCountStr = getNumString(getNum);
    resCom:GetChild("title").text = getNum;

    resCom:GetChild("icon").url = EnumConst.AtlasPath.ItemAtlas .. logicMgr.ItemManager.GetItemIcon(CurrencyEnum.MythicDungoesTicket);
    if tonumber(getNum) >= 1 then
        ifHaveKeyController.selectedIndex = 0;
        --txtCostCount.text = "[color=#FF0000]" .. hasCountStr .. "[/color]/1";
    else
        ifHaveKeyController.selectedIndex = 1;
        --txtCostCount.text = hasCountStr .. "/1";
    end
end
function UIMythicDungons.ScrollToView(index)
    if index <= 0 then
        index = 0
    end
    if index > this.maxCount then
        index = this.maxCount - 1
    end
    objLayerGroup:ScrollToView(index, false, true)
    --local item = objLayerGroup:GetChildAt(index)
end
function UIMythicDungons.ScrollToViewDelta(delta)
    local index = objLayerGroup:GetFirstChildInView()
    index = index + delta
    this.ScrollToView(index)
end
--里程碑奖励列表
function UIMythicDungons.refreshTaskReward(idx,obj)
    local cfg = taskRewardDatas[idx + 1];
    local data = logicMgr.ItemManager.getItemConstDatabyModelId(cfg[1]);
    local itemCtr = CtrlManager.GetCtrl(PanelNames.Item);
    data.num = cfg[2];
    itemCtr.initData(obj, data);
end

function UIMythicDungons.renderItem(idx, obj)

    local maxLayer = logicMgr.MythicDungeonsManager.getMaxLayer();

    local allCount = G.dataTable["t_global"]["80"].f_int_value + maxLayer;
    obj.touchable = true;

    if idx + 1 > allCount then
        obj:GetController("notselect").selectedIndex = 2;
        obj.touchable = false;
    --elseif maxLayer == idx + 1 then
    --    obj:GetController("notselect").selectedIndex = 1;
    else
        obj:GetController("notselect").selectedIndex = 0;
    end

    local layerText = obj:GetChild("LayerText");
    --local powerText = obj:GetChild("PowerText");
    local layerId = idx + 1;
    layerText.text = string.format("%d", layerId);
    local key = mythicConfig[tostring(layerId)]["f_MythicDungeonsMonsterTeamId"];
    --powerText.text = comPower[tostring(key)]["f_DispPower"];
    --obj:GetChild("SelectObj").visible = false;
    --local bgBtnObj = obj:GetChild("BgBtn");
    --obj.onClick:Clear();
    if not clicks[idx] then
        clicks[idx] = true
        obj.onClick:Add(function()
            this.onClickSelectLayer(obj, layerId);
            AudioManager.Play(1002)
        end);
    end
end

function UIMythicDungons.refreshEnterGroup()
    controllerGroup.selectedIndex = 0;
    btnEnterButton:GetController("isContinue").selectedIndex = 1;
    numLevelBtn:GetController("ifSelect").selectedIndex = 1;
    numLevelText.text = logicMgr.MythicDungeonsManager.getLayer();
    local getNum = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MythicDungoesTicket);
    resCom:GetChild("title").text = getNum;
    resCom:GetChild("icon").url = EnumConst.AtlasPath.ItemAtlas .. logicMgr.ItemManager.GetItemIcon(CurrencyEnum.MythicDungoesTicket);
    --objSelectGroup:SetActive(false);
    --objEnterGroup:SetActive(true);
    --txtLayer.text = string.format("%d", logicMgr.MythicDungeonsManager.getLayer());
    selectLayerId = logicMgr.MythicDungeonsManager.getLayer();
    this.refreshRewardList()
    this.refreshLeftTime();
    local key = mythicConfig[tostring(logicMgr.MythicDungeonsManager.getLayer())]["f_MythicDungeonsMonsterTeamId"];
    --layerPower.text = comPower[tostring(key)]["f_DispPower"];
    if timer == nil then
        timer = Timer.New(this.refreshLeftTime, 1, 99999999,true);
    else
        timer:Reset(this.refreshLeftTime, 1, 99999999,true)
    end
    timer:Start();
end

function UIMythicDungons.refreshLeftTime()
    local data = os.date("*t", Config.serverTime / 1000);
    data.hour = 23;
    data.min = 59;
    data.sec = 59;
    local time = os.time(data);
    txtTime.text = timeToTimeFormat(time - Config.serverTime / 1000);
end

function UIMythicDungons.onClickBack()
    closeUI(PanelNames.UIMythicDungons);
    if backFun then
        backFun();
    end
    if this.needShowHeadMenu then
        showUI(PanelNames.UIHeadMenu);
        this.needShowHeadMenu = nil;
    end
end

function UIMythicDungons.onClickSelect()
    if selectLayerId <= 0 then
        UISysTips.AddMsg(getLanguage("Sys_MythicDungeonSelectDesc"));
        AudioManager.Play(2010)
        TAManager.TrackByDictionary("mythic_click_enter_fail")
        return ;
    end
    if logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MythicDungoesTicket) <= 0 then
        local name = logicMgr.ItemManager.GetItemName(CurrencyEnum.MythicDungoesTicket)
        if name then
            UISysTips.AddMsg(name .. getLanguage("MythicDungeons_tips9"))
        end
        
        AudioManager.Play(2010)
        TAManager.TrackByDictionary("mythic_click_enter_fail")
        return ;
    end
    if controllerGroup.selectedIndex == 1 then
        local delaytime = 0
        if timerId then
            utimer.remove(timerId)
            timerId = nil
        end
        timerId = utimer.delayCall(function()
            utimer.remove(timerId)
            timerId = nil
            mythicDungeonsHandler.sendSelectLayer(selectLayerId);
            --永劫之境开启音效
            AudioManager.Play(2023)
            local _mythicDic = {}
            _mythicDic.mythic_level_id = selectLayerId
            TAManager.TrackByDictionary("mythic_click_enter_success",_mythicDic)
        end, delaytime * 1000)
    end
end

function UIMythicDungons.onClickEnter()
    local _layer = logicMgr.MythicDungeonsManager.getLayer()
    if _layer > 0 then
        local _mythicDic = {}
        _mythicDic.mythic_level_id = _layer
        --TAManager.TrackByDictionary("mythic_click_enter_success",_mythicDic)
        mythicDungeonsHandler.sendSelectLayer(_layer);

    else
        --永劫之境进入失败
        AudioManager.Play(2010)
        --TAManager.TrackByDictionary("mythic_click_enter_fail")
    end
end

function UIMythicDungons.onClickSelectLayer(go, layerId)
    selectLayerId = layerId;
    gameObject:GetController("ifSelect").selectedIndex = layerId <= 0 and 0 or 1;
    numLevelBtn:GetController("ifSelect").selectedIndex = layerId <= 0 and 0 or 1;
    this.refreshRewardList()
    if layerId <= 0 then
        dungeonPower.visible = false;

    else
        dungeonPower.visible = true;
        numLevelText.text = layerId;
        dungeonPower.text = HelperFunc.FormatResourceNum(comPower[tostring(layerId)]["f_DispPower"], true);
        powerStateController.selectedIndex = tonumber(logicMgr.HeroManager.GetTopHerosPower()) >= tonumber(comPower[tostring(layerId)]["f_DispPower"]) and 0 or 1
    end

    if layerId - 1 <= 0 then
        btnReduce.visible = false
    else
        btnReduce.visible = true;
    end
    local maxLayer = logicMgr.MythicDungeonsManager.getMaxLayer();
    local allCount = G.dataTable["t_global"]["80"].f_int_value + maxLayer;

    if layerId + 1 <= allCount then
        btnAdd.visible = true;
    else
        btnAdd.visible = false
    end

    if chooseLayerItem == nil then
        chooseLayerItem = go;
        go:GetController("notselect").selectedIndex = 1;

    else
        chooseLayerItem:GetController("notselect").selectedIndex = 0;
        go:GetController("notselect").selectedIndex = 1;
        chooseLayerItem = go;
    end
    this.ctrlIfShowLevel.selectedIndex = 0

    --for i = 1, #tableLayerObj do
    --    tableLayerObj[i]:GetChild("SelectObj").visible = (go.transform.parent == tableLayerObj[i].transform);
    --end
end

--- 获得秘境信息后走的流程

function UIMythicDungons.gotoFight()
    --播放音效
    --playCommonByType(Config.SoundType.ST_UI_battle_boss);

    BattleScene.pause();
    BattleScene.destroyScene();
    showUI(PanelNames.UILoadingBattle, FightManager.resList, function()
        DestoryUI(PanelNames.UILoadingBattle);
        hideOtherUI(true);
        showUI(PanelNames.UIBattleMain, this.onBattleFinish);
        FightManager.entrance();
    end);
end

function UIMythicDungons.onEnterFormation()
    this.refresh();
    if next(logicMgr.MythicDungeonsManager.getSelectedBuffId()) == nil and #logicMgr.MythicDungeonsManager.getWaitBuffIds() > 0 then
        showUI(PanelNames.UIMythicBuffSelect);
    else
        this.onSelectBuffSuccess();
    end
end

--[[function UIMythicDungons.onBattleResult()
    curPlayRound = 1;
    local roundInfo = logicMgr.MythicDungeonsManager.getRoundInfos()[curPlayRound];
    mythicDungeonsHandler.sendDungeon(roundInfo.fightId, roundInfo.result);
    logicMgr.FormationManager.SetFormation(EnumConst.FormationType.MythicDungeons, curFormations);
end]]

--[[function UIMythicDungons.onBattleFinish(isWin)
    --gameObject:SetActive(true);
    UIBottom.closeAllUI();
    curPlayRound = curPlayRound + 1;
    local roundInfos = logicMgr.MythicDungeonsManager.getRoundInfos();
    if curPlayRound <= #roundInfos then
        closeUI(PanelNames.UIBottom);
        local roundInfo = roundInfos[curPlayRound];
        mythicDungeonsHandler.sendDungeon(roundInfo.fightId, roundInfo.result, roundInfo.items);
    else
        UIBottom.enterAdventure();
        showUI(PanelNames.UIMythicDungons);
        this.refresh();
    end
end]]

function UIMythicDungons.onSelectBuffSuccess()
    -- --BUFF选择音效
    -- AudioManager.Play(2013)
    local function _checkFormation(formations)
        if formations then
            local fflag = true;
            for i = 1, #formations do
                local flag = false;
                for k = 1, #formations[i] do
                    if formations[i][k] ~= 0 then
                        flag = true;
                        break ;
                    end
                end
                if not flag then
                    fflag = false;
                    UISysTips.AddMsg(getLanguage("MythicDungeons_tips10"));
                    break ;
                end
            end
            if fflag then
                --closeUI(PanelNames.UIMythicDungons);
                -- closeUI(PanelNames.UIAdventureMain);
                logicMgr.FormationManager.SetFormation(EnumConst.FormationType.MythicDungeons, formations);
                curFormations = formations;
                local layerId = logicMgr.MythicDungeonsManager.getLayer();
                mythicDungeonsHandler.sendBoss(layerId, formations);
            end
        end
    end
    local id = logicMgr.MythicDungeonsManager.getLayer() > 0 and logicMgr.MythicDungeonsManager.getLayer() or selectLayerId;
    showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.INSTANCE, id, _checkFormation);
end
function UIMythicDungons.ClickShop()
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.MythicShop, true,btnGoShop) then
        return ;
    end
    logicMgr.UIShowManager.ShowUIShop(EnumConst.ShopType.mythicShop, nil, 4)
end
function UIMythicDungons.ClickAdd()
    local maxLayer = logicMgr.MythicDungeonsManager.getMaxLayer();

    local allCount = G.dataTable["t_global"]["80"].f_int_value + maxLayer;
    this.onClickSelectLayer(objLayerGroup:GetChildAt(selectLayerId), selectLayerId + 1);
    --this.ScrollToViewDelta(-1)
end
function UIMythicDungons.ClickReduce()
    this.onClickSelectLayer(objLayerGroup:GetChildAt(selectLayerId - 2), selectLayerId - 1);
    --this.ScrollToViewDelta(1)
end
function UIMythicDungons.onClickGetItem()
    --showUI(PanelNames.UISource, function () this.onClickBack(); end, CurrencyEnum.MythicDungoesTicket);
    this.showSourceController.selectedIndex = 1;
    this.showSourceList = {CurrencyEnum.MythicDungoesTicket}
    this.updateSource();
end

function UIMythicDungons.updateSource()
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, this.showSourceList, function ()
        this.showSourceController.selectedIndex = 0;
    end, function ()
        this.showSourceController.selectedIndex = 0;
        this.onClickBack();
    end );
end

return UIMythicDungons;
